package org.yookiee.support.config.interceptors;

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.yookiee.support.constants.I18nConstant;
import org.yookiee.support.core.DefaultTimeZone;
import org.yookiee.support.core.EasyLocale;
import org.yookiee.support.core.I18NContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * FileName I18NInterceptor
 * Package org.jeecg.config.i18n
 * Description
 * author cpstory
 * create 2023-09-27 11:10
 * version V1.0
 */
@Slf4j
public class EasyI18nInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String timeZone;
        String lang;
        String callService;

        timeZone = request.getHeader("X-TIME-ZONE");
        if (Strings.isNullOrEmpty(timeZone)) {
            timeZone = request.getParameter("timeZone");
        }

        lang = request.getHeader("X-LANG");
        if (Strings.isNullOrEmpty(lang)) {
            lang = request.getParameter("lang");
        }
        callService = request.getHeader("X-SERVICE");
        if (Strings.isNullOrEmpty(callService)) {
            callService = request.getParameter("callService");
        }

        if(log.isDebugEnabled()){
            log.debug("Interceptor request: {}", request.getRequestURI());
            log.debug("Interceptor Login Request timeZone: {}", timeZone);
            log.debug("Interceptor Login Request lang: {}", lang);
        }

        I18NContext.add(new EasyLocale(Strings.isNullOrEmpty(lang)? I18nConstant.ZH_CN : lang,
                Strings.isNullOrEmpty(timeZone)? DefaultTimeZone.defaultTimeZoneCode() : timeZone, callService));
        return true;
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        I18NContext.remove();
    }
}
